import router from '@/apps/admin/router.js'
import axios from "axios";

import {useRouter} from "vue-router";

// const router = useRouter()

const request = axios.create({
    baseURL: '/api',
    timeout: 60000,
});

export interface ApiResponse {
    code: number;        // 响应状态码
    msg: string;         // 提示信息
    data: object;             // 泛型，代表返回的数据结构
}

// 请求拦截器：自动加 token
request.interceptors.request.use((config) => {
        const token = localStorage.getItem('adminToken');
        if (token) {
            config.headers.Authorization = token
        }
        return config;
    },
    (err) => Promise.reject(err)
);

// 响应拦截器：统一处理 token 失效等情况
request.interceptors.response.use(
    (res) => res.data,
    (error) => {
        if (error.response && error.response.status === 401) {
            // token 失效或未登录，重定向到登录页
            console.log("401")
            window.location.href = '/admin.html#/login';
        }
        return Promise.reject(error);
    }
);

export function postJson(url: string, data: object): Promise<ApiResponse>{
    return request.post(url, data, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
}

export default request;
